package com.cszy.ewmxns.base


import android.content.res.ColorStateList
import com.csylhl.ewmksb.R
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.cszy.ewmxns.ext.toast
import com.gyf.immersionbar.ktx.immersionBar


import java.lang.reflect.ParameterizedType

abstract class BaseVMActivity<VM : BaseViewModel, VB : ViewBinding> : BaseActivity<VB, Any?>() {

    lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
//        ImmersionBar.with(this)
//            .barAlpha(0.0f)
//            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
//            .keyboardEnable(false)
//            .init()
       // immersionBar {}

        createViewModel()
        lifecycle.addObserver(mViewModel)
        registerEvent()
        super.onCreate(savedInstanceState)
    }


    fun setTitleWhiteStatusBar() {

        immersionBar {
            fitsSystemWindows(false)
            //白色状态栏，黑色字体
            statusBarColor(R.color.main_theme_color)
            statusBarDarkFont(true)
        }

        findViewById<TextView>(R.id.head_center_title).setTextColor(resources.getColor(R.color.white))

        findViewById<ImageView>(R.id.head_back).apply {
            backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(this@BaseVMActivity, R.color.white))
        }
    }

    private fun registerEvent() {
        mViewModel.ui.showDialog.observe(this) {
            showLoading(it)
        }
        mViewModel.ui.dismissDialog.observe(this) {
            dismissLoading()
        }
        mViewModel.ui.toast.observe(this) {
            toast(it)
        }
        mViewModel.ui.msgEvent.observe(this) {
            handleEvent(it)
        }
    }

    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val clazz = type.actualTypeArguments[0] as Class<VM>
            mViewModel = ViewModelProvider(viewModelStore, defaultViewModelProviderFactory)[clazz]
        }
    }

}